import request from '../request'
import adminTableEjs from '$com/adminTable'
import adminlistEjs from '$v/adminlist'
import adminApi from '../api/adminApi'
async function getAdminList(){
    let {code, msg, data:{adminList}} = await adminApi.getAdminList()
    $('#adminTable').html(adminTableEjs({adminList}))
}
async function saveAdmin() {
    // 获取数据
    let { adminName, password, rePassword } = document.adminForm
    adminName = adminName.value.trim()
    password = password.value.trim()
    rePassword = rePassword.value.trim()
    // 对数据进行判断
    if (!adminName.length) {
        toastr.error('用户名不能为空')
        return
    } else if (!password.length) {
        toastr.error('密码不能为空')
        return
    } else if (!rePassword.length) {
        toastr.error('确认密码不能为空')
        return
    } else if (password !== rePassword) {
        toastr.error('两次密码不相同')
        return
    }
    // 发送ajax
    let result = await adminApi.addAdmin({adminName,password,rePassword})
    let { msg, code }  = result
    if (code) {
        toastr.error(msg)
        return;
    } else {
        toastr.success(msg)
        // 关闭弹框
        $('#myModal').modal('hide')
        // 对数据惊醒清空
        document.adminForm.reset()
        await getAdminList()
    }

}
function addBtn() {
    $('#myModal').modal('show')
}

async function deleteAdmin(){
    if(!confirm('确定删除吗？')) return
    let _id = this.dataset.id
    let {code,msg} = await adminApi.deleteAdmin(_id)
    if(!code){
        toastr.success(msg)
        getAdminList()
    }else{
        toastr.error(msg)
    }
}
// 暴露 柯里化
export default function adminController(){
    return async (req, res, next) => {
        // 渲染页面到DOM中
        res.render(adminlistEjs())
        await getAdminList()
        // 对标题的渲染
        $('#titleShow').html('管理员列表')
        // 模态框开启
        $('#addAdminBtn').click(addBtn)
    
        // 模态框关闭
        $('#saveBtn').click(saveAdmin)

        // 点击删除
        $('#adminTable').on('click','.deleteBtn',deleteAdmin)
    }
}